import { bindCardConfirm } from '@/services/system/tenant';
import { ProForm, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Modal, message } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';

interface IBindCardComfirm {
  merchId: number | null;
  tenantName: string;
  close: (isRefresh: boolean) => void;
}

const BindCardComfirm = (props: IBindCardComfirm) => {
  const intl = useIntl();
  const formRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    formRef.current?.setFieldValue('tenantName', props.tenantName);
  }, []);

  const sumbitFun = useCallback(() => {
    formRef?.current.validateFieldsReturnFormatValue().then((res) => {
      console.log(res);
      setLoading(true);
      let data = {
        id: props.merchId,
        amount: res.amount,
      };
      bindCardConfirm(data)
        .then((res) => {
          setLoading(false);
          if (res.code === 200) {
            message.success(res.msg);
            props.close(true);
          } else {
            message.error(res.msg);
          }
        })
        .catch((res) => {
          setLoading(false);
          message.error(res.msg || res.message);
        });
    });
  }, []);
  return (
    <Modal
      width={640}
      title={intl.formatMessage({
        id: 'system.Tenant.merchIncome',
        defaultMessage: '绑卡确认',
      })}
      open={true}
      onCancel={() => {
        props.close(false);
      }}
      confirmLoading={loading}
      onOk={sumbitFun}
    >
      <ProForm
        formRef={formRef}
        submitter={{
          render: () => {
            return '';
          },
        }}
      >
        <ProFormText width="md" name="tenantName" label="商户名称" disabled></ProFormText>
        <ProFormText
          width="md"
          name="amount"
          label="打款金额"
          required
          rules={[
            {
              validator: (rules, value, callback) => {
                if (value === '') {
                  callback(new Error('打款金额不能为空'));
                  return;
                }
                if (isNaN(Number(value))) {
                  callback(new Error('请输入正确的金额'));
                  return;
                }
                if (value.split('.').length > 1 && value.split('.')[1].toString().length > 2) {
                  callback(new Error('请保留2位小数'));
                  return;
                }
                callback();
              },
            },
          ]}
        ></ProFormText>
      </ProForm>
    </Modal>
  );
};

export default BindCardComfirm;
